package com.example.api.controller.app;


import com.example.api.constant.StatusConst;
import com.example.api.dto.CustomerDTO;
import com.example.api.dto.UserDTO;
import com.example.api.exception.ParamException;
import com.example.api.pojo.Customer;
import com.example.api.properties.JWTProperties;
import com.example.api.service.CustomerService;
import com.example.api.utils.JWTUtil;
import com.example.api.utils.Result;
import com.example.api.vo.CustomerVO;
import com.example.api.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "会员接口")
@RestController
@RequestMapping("/app/customer")
public class CustomerController {

    @Resource
    JWTProperties jwtProperties;

    @Resource
    CustomerService customerService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<List<CustomerVO>> login(String phone, String password){
        //参数的校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)){
            throw new ParamException("账号和密码都不能为空");
        }
        CustomerVO customerVO = customerService.login(phone,password);
        if(customerVO==null){
            return Result.failure("账号或密码错误");
        }

        Map<String,Object> payload = new HashMap<>();
        payload.put(JWTUtil.CUSTOMER_ID,customerVO.getId());
        String token = JWTUtil.generateToken(payload,jwtProperties.getSecure(),jwtProperties.getExpire());

        Map<String,Object> data = new HashMap<>();
        data.put("token",token);
        data.put("userInfo",customerVO);

        return Result.ok("成功",data);
    }

    @ApiOperation("注册用户")
    @PostMapping
    public Result add(CustomerDTO customerDTO){
        customerService.add(customerDTO);
        return Result.ok("添加成功");
    }
}
